package com.my.admin.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.my.admin.enmu.ErrorTypeEnum;
import com.my.admin.entity.User;
import com.my.admin.service.ShiroService;
import com.my.admin.util.Rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
public class LoginController {

    @Autowired
    private ShiroService shiroService;

    @PostMapping("login")
    public Rest login(@RequestParam String username, @RequestParam String password) {
        if(StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Rest.err("用户名或密码不能空！");
        }
        User user = shiroService.getUserByUsername(username);
        if(user == null) {
            return Rest.err(ErrorTypeEnum.ERROR_400, "该用户不存在！");
        }else if(!user.isStatus()) {
            return Rest.err(ErrorTypeEnum.ERROR_400, "该用户已禁用！");
        }else if(!user.getPassword().equals(SecureUtil.md5(username + password))) {
            return Rest.err(ErrorTypeEnum.ERROR_400, "用户或密码不正确！");
        }else {
            String token = shiroService.createToken(user.getId());
            return Rest.ok("登录成功！").setData("token", token).setData("user", user.setPassword(""));
        }
    }

    @PostMapping("logout")
    public Rest logout(@RequestHeader("authentication-token") String token) {
        shiroService.logout(token);
        return Rest.ok("您已安全退出！");
    }

}
